
<template>
  <!-- 营销项目管理->项目总结查询 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="conditionFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="110"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_summary_dealer_inquire_index_01"
    >
      <template slot="controls">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="requestExportData"
        >下载</el-button>
      </template>
    </FilterTable>

    <Drawer
      :visible.sync="visibleDrawer"
      title="项目总结查询明细"
      destroyOnClose
      :containerStyle="{width:'70vw',minWidth:'1000px',height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-modal v-model="initData" :rowData="formData" @close="drawerClose" />
    </Drawer>

    <!-- 选择方案 -->
    <BaseDialog
      title="选择项目"
      :visible.sync="visibleDialogPro"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <programModal selectType="single" @close="selectModelBackPro" />
    </BaseDialog>
    <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="visibleDialog"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <modalModal selectType="multiple" @close="selectModelBack" />
    </BaseDialog>
  </div>
</template>

<script>
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import infoModal from './info';
import { getRegion } from '@/api/cms-common/dealerdata/index';
import programModal from '../../../program/push/select';
import modalModal from '@/pages/cms-common/model/indexFilter';
import { formatdateByDay } from '@/utils/index';
import { getBigMarketType, getSmallMarketType, getSummaryDlrInquireList, getSummaryDlrInquireExcelList } from '@/api/cms-api/projectOperating/plan/index';
import { porjectWithdraw} from '@/api/cms-api/projectOperating/plan';

export default {
  mixins: [dictionary],
  components: {
    infoModal,
    programModal,
    modalModal
  },
  //初始化数据  全局变量
  data() {
    return {
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      isSelectColumn: false,
      visibleDrawer: false,
      fetchParams: { is_no: 1 }, //参数
      fetchApi: getSummaryDlrInquireList, //ipa 接口
      visibleDealer: false,
      initDealerData: {}, //经销商弹窗参数
      dataSource: [], //返回经销商数组
      formData: {},
      initData: {},
      exportLoading: false,
      visibleDialogPro: false,
      visibleDialog: false,
      projectProgramId: 0, //项目id
      modelIdList: [],
      modelName: ''
    };
  },
  //方法、事件
  methods: {
    //导出
    async requestExportData() {
      let r = await this.$refs.conditionFilter.GET_FORM_DATA();
      let p = null;
      if (r != null && r.length > 1) {
        p = r[1];
      }
      p = Object.assign({}, { is_no: 1 }, p);
      //开始日期
      let realStartDate = p.realStartDate;
      //项目月份
      let activityMonth = p.activityMonth;
      p = Object.assign({}, { timestart: realStartDate[0] }, p);
      p = Object.assign({}, { timeend: realStartDate[1] }, p);
      p = Object.assign({}, { activityMonthStart: activityMonth[0] }, p);
      p = Object.assign({}, { activityMonthEnd: activityMonth[1] }, p);
      p = Object.assign({}, { is_no: 1 }, p);
      p = Object.assign({ projectProgramId: this.projectProgramId, modelIdList: this.modelIdList }, p);
      this.modelIdList = '';
      this.projectProgramId = '';
      this.fetchParams = Object.assign({}, p);



      this.exportLoading = true;
      // this.$refs.conditionFilter.SUBMIT_FORM();
      getSummaryDlrInquireExcelList(p).then(res => {
        exportExcelFile(res.data, '项目总结');
        this.exportLoading = false;
      });
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '项目方案',
          fieldName: 'projectProgramName',
          placeholder: '请选择',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialogPro()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目状态',
          fieldName: 'planStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictListRemoveCodes('2531', ['25311001', '25311002', '25311003', '25311004', '25311005', '25311006', '25311013'])
        },
        { type: 'INPUT', label: '项目编号', fieldName: 'planCode', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '项目名称', fieldName: 'projectName', placeholder: '请输入', initialValue: '' },
        { type: 'RANGE_DATE', label: '项目执行开始日期', fieldName: 'realStartDate', initialValue: '', placeholder: '请选择' },
        { type: 'RANGE_DATE', label: '项目月份', fieldName: 'activityMonth', dateType: 'monthrange', initialValue: '', placeholder: '请选择' },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modal',
          placeholder: '请选择',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.openModelDialog()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '项目大类',
          fieldName: 'projectMainClass',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: value => {
            this.initMarketTypeSmall(value);
          }
        },
        { type: 'SELECT', label: '项目小类', fieldName: 'projectSmallClass', placeholder: '请选择', initialValue: '', itemList: [] },
        { type: 'SELECT', label: '合作方式', fieldName: 'cooperationMethod', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2532') },
        { type: 'SELECT', label: '是否变更报备', fieldName: 'isChangePlan', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1004') },
        { type: 'SELECT', label: '是否抽检', fieldName: 'isCheck', placeholder: '请选择', initialValue: '', itemList:[{ text: '是', value: '是' }, { text: '否', value: '否' }]}
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'show')}>
                  明细
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.withdraw(props.row)}>
                  撤回
                </el-button>
              </div>
            );
          }
        },
        { title: '是否抽检', dataIndex: 'isCheck', fixed:"left",  sorter: true },
        { title: '项目编号', dataIndex: 'planCode', sorter: true },
        {
          title: '项目状态',
          dataIndex: 'planStatus',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.planStatus, '2531')}</span>;
          }
        },
        // { title: '事业部', dataIndex: 'orgId', sorter: true },
        // { title: '经销商代码', dataIndex: 'ownerCode', sorter: true },
        // { title: '经销商简称', dataIndex: 'dealerName', sorter: true },
        { title: '计划项目金额', dataIndex: 'planProjectAmount', sorter: true, numberFormat: true },
        { title: '计划批准金额', dataIndex: 'planApproveAmount', sorter: true, numberFormat: true },
        {
          title: '计划核销比例',
          dataIndex: 'planCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.planCancellationRatio != null) {
              return <span slot="append">{props.row.planCancellationRatio}%</span>;
            }
          }
        },
        { title: '实际项目金额', dataIndex: 'realProjectAmount', sorter: true, numberFormat: true },
        { title: '实际批准金额', dataIndex: 'realApproveAmount', sorter: true, numberFormat: true },
        {
          title: '实际核销比例',
          dataIndex: 'realCancellationRatio',
          sorter: true,
          render: props => {
            if (props.row.realCancellationRatio != null) {
              return <span slot="append">{props.row.realCancellationRatio}%</span>;
            }
          }
        },
        {
          title: '合作方式',
          dataIndex: 'cooperationMethod',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.cooperationMethod, '2532')}</span>;
          }
        },
        { title: '计划支持场次/投放天数', dataIndex: 'planTimeDay', sorter: true },
        { title: '实际支持场次/投放天数', dataIndex: 'realTimeDay', sorter: true },
        { title: '目标订单数', dataIndex: 'targetOrderNum', sorter: true },
        { title: '目标集客数', dataIndex: 'targetGuestsNum', sorter: true },
        { title: '目标留档数', dataIndex: 'targetRetentionNum', sorter: true },
        { title: '实际订单数', dataIndex: 'realOrderNum', sorter: true },
        { title: '实际集客数', dataIndex: 'realGuestsNum', sorter: true },
        { title: '实际留档数', dataIndex: 'realRetentionNum', sorter: true },
        {
          title: '项目月份',
          dataIndex: 'activityMonth',
          sorter: true,
          dateFormat: 'YYYY年MM月'
          // render: props => {
          //   return <span>{formatdateByDay(props.row.activityMonth)} </span>;
          // }
        },
        {
          title: '项目车型',
          dataIndex: 'modelLists',
          sorter: true
        },
        { title: '项目大类', dataIndex: 'projectMainClassName', sorter: true },
        { title: '项目小类', dataIndex: 'projectSmallClassName', sorter: true },
        { title: '项目名称', dataIndex: 'projectName', sorter: true },
        { title: '方案编号', dataIndex: 'programCode', sorter: true },
        { title: '方案名称', dataIndex: 'programName', sorter: true },
        {
          title: '项目执行开始日期',
          dataIndex: 'realStartDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realStartDate)} </span>;
          }
        },
        {
          title: '项目执行结束日期',
          dataIndex: 'realEndDate',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.realEndDate)} </span>;
          }
        },
        {
          title: '是否变更报备',
          dataIndex: 'isChangePlan',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isChangePlan, '1004')}</span>;
          }
        }
      ];
    },
    // 撤回
      async withdraw(row){
          
          // let row = this.formData;
          let status = row.planStatus;
          let planId = row.planId;//记录的主键
          if(status!="25311008"){//总结已提交
              this.$notify.error({title: '提示信息',message:'您好，只能撤回已提交的总结！'});
              return;
          } 
          
          this.$confirm('是否撤回', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(async() => {
                  this.dataParams = {
                      planId:planId,
                      type:"summary"
                  }
                  let res =  await porjectWithdraw(this.dataParams);
                  this.validReturnDate(res);
          }).catch(() => {
              this.$notify.info({title: '提示信息',message:'操作取消！'});
          });
      }, 
      validReturnDate(res){
          if (res.resultCode === 200) {
              this.$notify.success({title: '提示信息',message:'操作成功!'});
              // 重新加载
              this.fetchParams = { ...this.fetchParams };
          }else {
              this.$notify.error({title: '提示信息',message:res.errMsg||'操作失败!'});
              
          }
      },
    //日期格式化年月
    formatDatesNoDay: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      return year + '-' + month;
    },
    //日期格式化年月日
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    //详情
    drawerHandle(row, type) {
      //逻辑自己写
      this.initData = {
        row: row,
        type: type //add/edit/show
      };
      this.formData = row;
      this.visibleDrawer = true;
    },
    //关闭详情
    drawerClose() {
      this.visibleDrawer = false;
        // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //搜索回调
    changeHandle(data) {
      //开始日期
      let realStartDate = data.realStartDate;
      //项目月份
      let activityMonth = data.activityMonth;
      data = Object.assign({}, { timestart: realStartDate[0] }, data);
      data = Object.assign({}, { timeend: realStartDate[1] }, data);
      data = Object.assign({}, { activityMonthStart: activityMonth[0] }, data);
      data = Object.assign({}, { activityMonthEnd: activityMonth[1] }, data);
      data = Object.assign({}, { is_no: 1 }, data);
      data = Object.assign({ projectProgramId: this.projectProgramId, modelIdList: this.modelIdList }, data);
      // this.modelIdList = '';
      // this.projectProgramId = '';
      this.fetchParams = Object.assign({}, data);
    },
    //取项目大类
    async initBigMarketType() {
      let res = [];
      let rd = await getBigMarketType();
      for (let i in rd.data) {
        res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
      }
      this.topFilterInit[7].itemList = res;
    },
    //取项目小类
    async initMarketTypeSmall(parentTypeId) {
      let res = [];
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').initialValue = '';
      this.topFilterInit.find(item => item.fieldName === 'projectSmallClass').itemList = [];
      if (parentTypeId != '') {
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getSmallMarketType(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].typeName, value: rd.data[i].typeId });
        }
        this.topFilterInit[8].itemList = res;
      }
    },
    //项目方案弹窗打开
    openModelDialogPro() {
      this.visibleDialogPro = true;
    },
    //项目弹窗关闭
    selectModelBackPro(data) {
      // console.log('---data:', data);
      if (data && data.data && typeof data.data != null) {
        this.projectProgramId = data.data[0].projectProgramId;

        this.topFilterInit[0].initialValue = data.data[0].programName;
      }

      this.visibleDialogPro = false; //关闭弹窗
    },
    //车型弹窗打开
    openModelDialog() {
      this.visibleDialog = true;
    },
    //车型弹窗关闭
    selectModelBack(data) {
      if (data && data.data && typeof data.data != null) {
        //清空数据
        this.modelIdList = '';
        this.modelName = '';
        //循环返回数据
        data.data.forEach(x => {
          //使用逗号分隔拼接车型ID
          if (this.modelIdList == '') {
            this.modelIdList = x.modelId;
          } else {
            this.modelIdList += ',' + x.modelId;
          }

          //使用逗号分隔拼接车型名称
          if (this.modelName == '') {
            this.modelName = x.modelName;
          } else {
            this.modelName += ',' + x.modelName;
          }
        });

        //显示车型名称
        this.topFilterInit[6].initialValue = this.modelName;
      }

      this.visibleDialog = false; //关闭弹窗
    }
  },
  mounted() {
    //初始化项目大类
    this.initBigMarketType();
  }
};
</script>

<style scoped>
</style>
